/* Chris Baird,, <chris.j.baird@gmail.com> August 2022
 * --
 * Credit to hofuku@notabug for pointing out I'd forgot
 * the random seeding.
 * https://notabug.org/vk2cjb/random_coding/issues/1
 */

#include <stdio.h>
#include <unistd.h>

// With an xterm maximized to a 1920x1080 screen..
#define WIDTH (640)
#define HEIGHT (320)

// ----------------------------------------------------------------------

void bralliemap (int c)
{
  int c1, c2;

  c1 = 160;
  if (c & 8)   c1 += 1;
  if (c & 128) c1 += 2;

  c2 = 128 | (c & 7) | ((c & 112) >> 1);

  printf("%c%c%c", 226, c1, c2);
}

void doplot (int s)
{
  static const int e[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
  static int x = 0, y = 0, row[WIDTH>>1];
  int x1, y1, x2, b, i;

  x1 = (x & 1) << 2;
  x2 = x >> 1;
  y1 = y & 3;

  b = e[x1+y1];

  if (s) row[x2] |= b;
  else   row[x2] &= ~b;

  if (++x == WIDTH)
    {
      x = 0;
      if (++y == 4)
	{
	  for (i = 0; i < WIDTH>>1; i++)
	    {
	      bralliemap (row[i]);
	      row[i] = 0;
	    }
	  printf ("\n");
	  y = 0;
	}
    }
}

// ----------------------------------------------------------------------

#include <math.h>
#include <stdlib.h>
#include <time.h>

#define ncharges (200)

int main (void)
{
  int s, x, y, i;
  int chargex[ncharges], chargey[ncharges], charge[ncharges];

  srand(time(NULL));

  for (i = 0; i < ncharges; i++)
    {
      chargex[i] = rand() % WIDTH;
      chargey[i] = rand() % HEIGHT;
      charge[i] = (rand() % 100) - 50;
    }

  for (y = 0; y < HEIGHT; y++)
    for (x = 0; x < WIDTH; x++)
      {
	float c = 0;
	for (i = 0; i < ncharges; i++)
	  {
	    c += charge[i] /
	      (sqrtf ((x-chargex[i])*(x-chargex[i]) +
		      (y-chargey[i])*(y-chargey[i])));
	  }

	s = ((c - floorf(c)) > 0.5) ? 1 : 0;
	doplot (s);
      }
}

// ----------------------------------------------------------------------
